package com.lc.afbx.util;

import android.content.Context;
import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.widget.EditText;

/**
 * Created by Administrator on 2016/7/19.
 */
public class MEditTextListener implements TextWatcher {

    private final EditText editText;
    private CharSequence temp = "";
    private Context context;
    private int maxLength;

    public MEditTextListener(Context context, int length, EditText editText) {
        this.context = context;
        this.maxLength = length;
        this.editText = editText;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        temp = s;
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        Editable editable = editText.getText();

        //不让输入空格的方法
        if (s.toString().contains(" ")) {
            String[] str = s.toString().split(" ");
            String str1 = "";
            for (int i = 0; i < str.length; i++) {
                str1 += str[i];
            }
            editText.setText(str1);

            editText.setSelection(start);

        }

        int len = editable.length();

        if (len > maxLength) {
            int selEndIndex = Selection.getSelectionEnd(editable);
            String str = editable.toString();
            //截取新字符串
            String newStr = str.substring(0, maxLength);
            editText.setText(newStr);
            editable = editText.getText();

            //新字符串的长度
            int newLen = editable.length();
            //旧光标位置超过字符串长度
            if (selEndIndex > newLen) {
                selEndIndex = editable.length();
            }
            //设置新光标所在的位置
            Selection.setSelection(editable, selEndIndex);

        }
    }

    @Override
    public void afterTextChanged(Editable s) {

        if (temp.length() > maxLength) {
            MyToast.showToast("最多输入" + maxLength + "位", context);
        }
    }
}
